package com.lu.dao.impl;

import com.lu.dao.BaseDao;
import com.lu.dao.BuyDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BuyDaoImpl extends BaseDao implements BuyDao {
    @Override
    public int updateSeller(int seller, double money) {
        String sql = "UPDATE `User` SET Balance = Balance + ? WHERE UId = ?";
        Object[] parma = {money,seller};
        return executeUpdate(sql,parma);
    }

    @Override
    public int updateBuyer(int buyer, double money) {
        String sql = "UPDATE `User` SET Balance = Balance - ? WHERE UId = ?";
        Object[] parma = {money,buyer};
        return executeUpdate(sql,parma);
    }

    @Override
    public double getBuyerMoney(int buyer) {
        double balance = 0;
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String sql = "SELECT Balance FROM `User` WHERE UId = ?";

        try {
            con = getCon();
            pstmt = con.prepareStatement(sql);
            pstmt.setInt(1,buyer);
            rs = pstmt.executeQuery();
            if(rs.next()){
                balance = rs.getInt("Balance");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            closeAll(con,pstmt,rs);
        }

        return balance;
    }
}
